<template>
  <div class="detail-container">
    <div class="header">
      <button @click="goBack" class="back-btn">返回</button>
      <h2>帖子详情</h2>
    </div>
    
    <!-- 加载状态 -->
    <div v-if="loading" class="loading">
      <p>加载中...</p>
    </div>
    
    <div class="detail-body" v-else-if="post">
      <h2 class="detail-title">{{ post.title }}</h2>
      
      <div class="detail-meta">
        <span class="tag" v-if="post.tag">{{ post.tag }}</span>
        <span class="view-count">浏览量：{{ post.viewCount || 0 }}</span>
        <span class="author">发帖人：{{ postAuthorName || '未知用户' }}</span>
        <span class="collect-time">收藏时间：{{ formatDate(post.favoriteCreatedAt) }}</span>
      </div>
      
      <div class="detail-content">
        <h4>帖子内容：</h4>
        <div class="content-text">{{ post.content }}</div>
      </div>

      <!-- 评论区域 -->
      <div class="comments-section">
        <div class="comments-header">
          <h3>评论 ({{ comments.length }})</h3>
        </div>

        <!-- 评论列表 -->
        <div class="comments-list">          
          <div v-if="comments.length === 0" class="no-comments">
            <p>暂无评论</p>
          </div>
          
          <div v-else>
            <div v-for="comment in comments" :key="comment.commentId || comment.id" class="comment-item">
              <div class="comment-header">
                <span class="comment-author">{{ comment.userName || '未知用户' }}</span>
                <span class="comment-time">{{ formatDate(comment.createdAt || comment.createTime) }}</span>
              </div>
              <div class="comment-content">{{ comment.content }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 错误状态 -->
    <div v-else class="error-state">
      <p>获取帖子详情失败，请稍后重试</p>
    </div>
    
    <div class="footer">
      <button @click="handleUnfavorite" class="delete-btn">取消收藏</button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useUserStore } from '@/store/user';
import axios from 'axios';

const route = useRoute();
const router = useRouter();
const userStore = useUserStore();

const post = ref(null);
const loading = ref(false);
const comments = ref([]);
const postAuthorName = ref('');
const userNameCache = ref({});

// 获取用户名（带缓存）
const getUserName = async (userId) => {
  if (!userId) return '未知用户';
  
  // 检查缓存
  if (userNameCache.value[userId]) {
    return userNameCache.value[userId];
  }
  
  try {
    const response = await axios.get('/api/user/find', {
      params: { id: userId }
    });
    
    if (response.data && response.data.username) {
      const userName = response.data.username;
      // 缓存用户名
      userNameCache.value[userId] = userName;
      return userName;
    } else {
      return '未知用户';
    }
  } catch (error) {
    console.error(`获取用户${userId}信息失败:`, error);
    return '未知用户';
  }
};

// 获取发帖人用户名
const fetchPostAuthorName = async (userId) => {
  if (userId) {
    postAuthorName.value = await getUserName(userId);
  }
};

// 获取评论中所有用户的用户名
const fetchCommentUserNames = async () => {
  const userIds = [...new Set(comments.value.map(comment => comment.userId).filter(id => id))];
  
  // 并行获取所有用户名
  const userNamePromises = userIds.map(async (userId) => {
    const userName = await getUserName(userId);
    return { userId, userName };
  });
  
  try {
    const userNames = await Promise.all(userNamePromises);
    
    // 将用户名添加到评论数据中
    comments.value = comments.value.map(comment => {
      const userInfo = userNames.find(user => user.userId === comment.userId);
      return {
        ...comment,
        userName: userInfo ? userInfo.userName : '未知用户'
      };
    });
  } catch (error) {
    console.error('获取评论用户名失败:', error);
    // 如果获取失败，给所有评论设置默认用户名
    comments.value = comments.value.map(comment => ({
      ...comment,
      userName: '未知用户'
    }));
  }
};

// 获取收藏详情
const fetchCollectionDetail = async () => {
  loading.value = true;
  try {
    const favoriteId = route.params.id;
    
    // 获取当前用户ID
    const userId = userStore.userId;
    if (!userId) {
      alert('请先登录');
      router.push('/login');
      return;
    }
    
    console.log('开始获取收藏详情，favoriteId:', favoriteId, 'userId:', userId);
    
    // 获取用户所有收藏，这里设置较大的size来获取所有收藏
    const response = await axios.get(`/user/post/favorites/${userId}`, {
      params: {
        current: 1,
        size: 1000 // 获取所有收藏用于查找
      }
    });
    
    console.log('后端返回的收藏数据:', response.data);
    
    // 后端返回的是PageInfo对象，数据在list属性中
    if (response.data && response.data.list && Array.isArray(response.data.list)) {
      const favoritesList = response.data.list;
      
      // 根据favoriteId找到对应的帖子
      const foundPost = favoritesList.find(item => {
        // 尝试多种可能的字段名匹配
        return item.favoriteId == favoriteId || 
               item.id == favoriteId || 
               item.userPostId == favoriteId ||
               item.postId == favoriteId;
      });
      
      console.log('找到的帖子数据:', foundPost);
      
      if (foundPost) {
        post.value = foundPost;
        
        // 从帖子数据中提取评论信息
        extractComments(foundPost);
        
        // 获取发帖人用户名
        await fetchPostAuthorName(foundPost.userId || foundPost.authorId);
        
        // 获取评论中所有用户的用户名
        await fetchCommentUserNames();
      } else {
        console.error('未找到对应的收藏帖子，favoriteId:', favoriteId);
        console.log('可用的收藏列表:', favoritesList);
        alert('未找到该收藏帖子');
        goBack();
      }
    } else if (response.data && Array.isArray(response.data)) {
      // 如果后端直接返回数组（兼容处理）
      const favoritesList = response.data;
      const foundPost = favoritesList.find(item => 
        item.favoriteId == favoriteId || 
        item.id == favoriteId ||
        item.userPostId == favoriteId ||
        item.postId == favoriteId
      );
      
      if (foundPost) {
        post.value = foundPost;
        extractComments(foundPost);
        await fetchPostAuthorName(foundPost.userId || foundPost.authorId);
        await fetchCommentUserNames();
      } else {
        alert('未找到该收藏帖子');
        goBack();
      }
    } else {
      console.error('后端返回数据格式异常:', response.data);
      alert('获取收藏详情失败：数据格式错误');
      goBack();
    }
  } catch (error) {
    console.error('获取收藏详情失败:', error);
    alert('获取收藏详情失败，请稍后重试');
    goBack();
  } finally {
    loading.value = false;
  }
};

// 从帖子数据中提取评论信息
const extractComments = (postData) => {
  try {
    // 根据可能的字段名提取评论数据
    if (postData.comments && Array.isArray(postData.comments)) {
      comments.value = postData.comments;
    } else if (postData.commentList && Array.isArray(postData.commentList)) {
      comments.value = postData.commentList;
    } else if (postData.postComments && Array.isArray(postData.postComments)) {
      comments.value = postData.postComments;
    } else if (postData.replies && Array.isArray(postData.replies)) {
      comments.value = postData.replies;
    } else {
      // 如果没有找到评论字段，设为空数组
      comments.value = [];
    }
    
    console.log('提取到的评论数据:', comments.value);
  } catch (error) {
    console.error('提取评论数据失败:', error);
    comments.value = [];
  }
};

// 取消收藏
const handleUnfavorite = async () => {
  if (!confirm('确定要取消收藏这个帖子吗？')) return;
  
  try {
    const favoriteId = route.params.id;
    console.log('准备取消收藏，favoriteId:', favoriteId);
    
    const response = await axios.delete(`/user/post/favorites/${favoriteId}`);
    
    console.log('取消收藏响应:', response.data);
    
    // 后端返回boolean，true表示成功
    if (response.data === true) {
      alert('取消收藏成功！');
      goBack();
    } else {
      alert('取消收藏失败，请重试！');
    }
  } catch (error) {
    console.error('取消收藏失败:', error);
    if (error.response && error.response.status === 404) {
      alert('收藏记录不存在或已被删除');
    } else {
      alert('取消收藏失败，请重试！');
    }
  }
};

// 格式化日期
const formatDate = (date) => {
  if (!date) return '';
  try {
    const d = new Date(date);
    if (isNaN(d.getTime())) {
      return date;
    }
    return d.toLocaleDateString() + ' ' + d.toLocaleTimeString();
  } catch (error) {
    return date;
  }
};

// 返回上一页
const goBack = () => {
  router.go(-1);
};

onMounted(async () => {
  await userStore.initialize();
  await fetchCollectionDetail();
});
</script>

<style scoped>
.detail-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 2px solid #f0f0f0;
}

.back-btn {
  background: none;
  border: none;
  padding: 8px 16px;
  margin-right: 20px;
  cursor: pointer;
  font-size: 16px;
  color: #1890ff;
  transition: color 0.3s;
}

.back-btn:hover {
  color: #40a9ff;
}

.loading {
  text-align: center;
  padding: 40px;
  color: #666;
}

.error-state {
  text-align: center;
  padding: 60px;
  color: #ff4d4f;
}

.detail-title {
  margin: 0 0 20px 0;
  color: #333;
  font-size: 28px;
  line-height: 1.4;
  font-weight: 600;
}

.detail-meta {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 30px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 8px;
  font-size: 14px;
  flex-wrap: wrap;
}

.tag {
  background-color: #e6f7ff;
  color: #1890ff;
  padding: 4px 12px;
  border-radius: 16px;
  font-weight: 500;
}

.view-count {
  color: #666;
  display: flex;
  align-items: center;
}

.view-count::before {
  content: "👁";
  margin-right: 4px;
}

.author {
  color: #1890ff;
  font-weight: 600;
  background-color: #e6f7ff;
  padding: 4px 8px;
  border-radius: 4px;
  display: flex;
  align-items: center;
}

.author::before {
  content: "👤";
  margin-right: 4px;
}

.collect-time {
  color: #999;
  font-style: italic;
}

.detail-content {
  margin-bottom: 40px;
}

.detail-content h4 {
  margin: 0 0 15px 0;
  color: #333;
  font-size: 18px;
  font-weight: 500;
}

.content-text {
  line-height: 1.8;
  color: #333;
  padding: 20px;
  background-color: #fafafa;
  border-left: 4px solid #1890ff;
  border-radius: 0 6px 6px 0;
  white-space: pre-wrap;
  word-break: break-word;
  font-size: 16px;
  min-height: 120px;
}

.footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 40px;
  padding-top: 20px;
  border-top: 1px solid #f0f0f0;
}

/* 评论区域样式 */
.comments-section {
  border-top: 1px solid #f0f0f0;
  padding-top: 30px;
  margin-top: 30px;
  margin-bottom: 30px;
}

.comments-header {
  margin-bottom: 20px;
}

.comments-header h3 {
  margin: 0;
  color: #333;
  font-size: 20px;
  font-weight: 600;
}

.no-comments {
  text-align: center;
  padding: 40px;
  color: #999;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.comment-item {
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 12px;
  background-color: #fff;
  transition: all 0.3s;
}

.comment-item:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border-color: #d9d9d9;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  font-size: 13px;
}

.comment-author {
  color: #1890ff;
  font-weight: 600;
  background-color: #e6f7ff;
  padding: 2px 8px;
  border-radius: 4px;
  display: flex;
  align-items: center;
}

.comment-author::before {
  content: "💬";
  margin-right: 4px;
}

.comment-time {
  color: #999;
  font-style: italic;
}

.comment-content {
  color: #333;
  line-height: 1.6;
  font-size: 15px;
  white-space: pre-wrap;
  word-break: break-word;
}

.delete-btn {
  background-color: #ff4d4f;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s;
  box-shadow: 0 2px 4px rgba(255, 77, 79, 0.2);
}

.delete-btn:hover {
  background-color: #ff7875;
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(255, 77, 79, 0.3);
}

.delete-btn:active {
  transform: translateY(0);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .detail-container {
    padding: 15px;
  }
  
  .header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .back-btn {
    margin-right: 0;
    margin-bottom: 10px;
  }
  
  .detail-title {
    font-size: 24px;
  }
  
  .detail-meta {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .content-text {
    padding: 15px;
    font-size: 15px;
  }
  
  .footer {
    text-align: center;
  }
  
  .delete-btn {
    width: 100%;
    max-width: 200px;
  }
  
  .comment-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }
  
  .comment-content {
    font-size: 14px;
  }
}

@media (max-width: 480px) {
  .detail-container {
    padding: 10px;
  }
  
  .detail-title {
    font-size: 20px;
  }
  
  .detail-meta {
    font-size: 13px;
  }
  
  .content-text {
    font-size: 14px;
    padding: 12px;
  }
  
  .comments-header h3 {
    font-size: 18px;
  }
  
  .comment-item {
    padding: 12px;
  }
  
  .comment-content {
    font-size: 13px;
  }
}
</style>